package main_form

import (
	Widget "clientDemo/tools/websockettool/Widget"
	"fmt"
	"github.com/lxn/walk"
	"github.com/lxn/walk/declarative"
	"github.com/lxn/win"
	"log"
	"unsafe"
)

var Composite1 *walk.Composite
var Label1 *walk.Label
var Button1 *walk.PushButton

// MainForm 主窗口: 加载底层窗口页面
func MainForm(logger *log.Logger) {

	mw, err := walk.NewMainWindow()
	if err != nil {
		walk.MsgBox(mw, "错误", "程序打开失败", walk.MsgBoxIconError)
		walk.App().Exit(0)
		return
	}
	mainScene, err := LoadMainScene("skin/MainScene/MainScene.xml")
	if err != nil {
		ShowMsgBox(mw, "你的窗口配置文件出错")
		return
	}
	widgetSkin, err := LoadSkinConfig("skin/WidgetTemplate/WidgetSkin.xml")
	if err != nil {
		ShowMsgBox(mw, "模板文件出错")
		return
	}
	_ = widgetSkin
	//// 设置窗体标题
	//mw.SetTitle(`你好世界！`)
	//
	//// 设置窗体的宽高
	//mw.SetWidth(400)
	//mw.SetHeight(400)
	//
	//// 设置窗体生成在屏幕的正中间
	//// 窗体横坐标 = ( 屏幕宽度 - 窗体宽度 ) / 2
	//// 窗体纵坐标 = ( 屏幕高度 - 窗体高度 ) / 2
	//mw.SetX((int(win.GetSystemMetrics(0)) - mw.Width()) / 2)
	//mw.SetY((int(win.GetSystemMetrics(main.manifest)) - mw.Height()) / 2)
	//
	//// 设置窗体为显示状态（默认：隐藏状态）
	//mw.Show()
	//
	//// 运行窗体
	//mw.Run()
	w := Widget.CreateWindows(mw, mainScene.Title, mainScene.MainWidth, mainScene.MainHeight)
	title := Widget.CreateMainForm()
	title.SetTitleText("                        主窗口信息：")
	title.SetLineEdit("这是主窗口llll")
	w.AddChild(title.Sprite)

	mainWindow, _ := walk.NewMainWindow()
	customButton1, _ := walk.NewPushButton(w.Window)
	customButton2, _ := walk.NewPushButton(mainWindow)

	customButton1.Paint().SetCustom(func(canvas *walk.Canvas, updateBounds walk.Rectangle) error {
		bounds := customButton1.BoundsPixels()

		if canvas.BeginPaint(bounds); err != nil {
			return err
		}
		defer canvas.EndPaint()

		graphicsContext, _ := canvas.GraphicsContext()

		graphicsContext.FillRectangle(walk.RGB(255, 0, 0), bounds)
		graphicsContext.DrawRectangle(walk.RGB(0, 0, 0), bounds)

		return nil
	})

	customButton2.Paint().SetCustom(func(canvas *walk.Canvas, updateBounds walk.Rectangle) error {
		bounds := customButton2.BoundsPixels()

		if canvas.BeginPaint(bounds); err != nil {
			return err
		}
		defer canvas.EndPaint()

		graphicsContext, _ := canvas.GraphicsContext()

		graphicsContext.FillRectangle(walk.RGB(0, 0, 255), bounds)
		graphicsContext.DrawRectangle(walk.RGB(0, 0, 0), bounds)

		return nil
	})

	mainWindow.SetLayout(walk.NewHBoxLayout())
	mainWindow.Layout().SetMargins(walk.Margins{10, 10, 10, 10})

	mainWindow.Layout().AddWidget(customButton1)
	mainWindow.Layout().AddWidget(customButton2)

	txt := Widget.CreateWidgetTxt()
	txt.SetTitleText("                        211主窗口信息：")
	w.AddChild(txt.Sprite)

	ed := Widget.CreateWidgetEdit()
	ed.SetLineEdit(" desfes")
	w.AddChild(ed.Sprite)

	bt0 := Widget.CreateWidgetButton()
	bt0.SetButtonText(" Button")
	w.AddChild(bt0.Sprite)

	w.AddChild(&declarative.Composite{
		//Layout: declarative.VBox{},
		Children: []declarative.Widget{
			declarative.Label{
				Text:     "Username:",
				AssignTo: &Label1,
			},
			declarative.PushButton{
				Text: "Login",
				OnClicked: func() {
					//text := lineEdit.Text()
					//log.Println("Text:", text)
				},
				AssignTo: &Button1,
				//Bounds:   Rectangle{X: 100, Y: 100, Width: 75, Height: 25},
			},
		},
		AssignTo: &Composite1,
	})

	lb := Widget.CreateListBox()

	bt := Widget.CreateButton()
	bt.SetButtonText("添加")
	bt.SetButtonFunc(func() { addList(lb) })
	w.AddChild(bt.Sprite)

	bt2 := Widget.CreateButton()
	bt2.SetButtonText("清空")
	bt2.SetButtonFunc(func() { ClearList(lb) })
	w.AddChild(bt2.Sprite)

	/*
		var listBox *walk.ListBox
		var timer *time.Timer
		items := []string{"Time"}
		// 在主线程中处理通道中的数据并更新UI
		timer = time.NewTimer(time.Second) // 创建定时器，每秒触发一次
			go func() {
			for range timer.C {
				now := time.Now().Format("15:04:05")
				items[0] = now
				listBox.Synchronize(func() {
					listBox.SetModel(items)
				})
			}
		}()*/

	//以上代码创建了一个名为 "ListBox Timer Example" 的窗口，并在窗口中放置了一个 `ListBox` 控件。然后，创建了一个定时器，并在定时器触发时更新 `ListBox` 中的时间文本。

	/*	l := declarative.ListBox{
			AssignTo: &listBox,
			Model:    items,
		}
		w.AddChild(l)*/
	w.AddChild(lb.Sprite)
	//items := []string{
	//	"Item main.manifest",
	//	"Item 2",
	//	"Item 3",
	//}
	//w.Window.Children = append(w.Window.Children, &declarative.ListBox{
	//	//AssignTo: &lb, // 将列表框赋值给变量lb，以便后续操作
	//	Model: items,
	//})
	//w.Children = append(w.Children, Widget.CreateMainForm())
	//w.Children = append(w.Children, Widget.CreateButton(addList))
	// 在主线程中处理通道中的数据并更新UI

	// 启动主循环
	if err := w.Create(); err != nil {
		fmt.Println("Failed to create window:", err)
		return
	}

	/*	// 关闭定时器和窗口
		defer timer.Stop()
		defer listBox.Dispose()*/
	centerWindow(mw)
	setSysTray(logger, mw)
}
func centerWindow(window *walk.MainWindow) {
	handle := window.Handle()
	monitor := win.MonitorFromWindow(handle, win.MONITOR_DEFAULTTONEAREST)
	var mi win.MONITORINFO
	mi.CbSize = uint32(unsafe.Sizeof(mi))
	win.GetMonitorInfo(monitor, &mi)

	screenWidth := mi.RcWork.Right - mi.RcWork.Left
	screenHeight := mi.RcWork.Bottom - mi.RcWork.Top

	windowWidth := int32(window.Width())
	windowHeight := int32(window.Height())

	x := mi.RcWork.Left + (screenWidth-windowWidth)/2
	y := mi.RcWork.Top + (screenHeight-windowHeight)/2

	win.SetWindowPos(handle, 0, x, y, windowWidth, windowHeight, win.SWP_NOZORDER|win.SWP_NOACTIVATE)
}

func addList(lb *Widget.XListBox) {
	print("TestItem.TestC1.TestC()")
	lb.AddBoxText("test1")
}
func ClearList(lb *Widget.XListBox) {
	lb.ClearBoxText()
	Label1.SetBounds(walk.Rectangle{X: 100, Y: 100, Width: 100, Height: 20})
	Button1.SetBounds(walk.Rectangle{X: 200, Y: 100, Width: 75, Height: 25})
}
